var createError = require('http-errors')
var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')
// 引入这个文件是为了查看post请求里面的body参数
var bodyParser = require('body-parser')

// 引入路由文件
var indexRouter = require('./routes/index')
var usersRouter = require('./routes/users')

var app = express()

// 改写启动目录
var http = require('http')
var server = http.createServer(app)

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'jade')

app.use(logger('dev'))
// app.use(express.json())
// app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

// 获取post请求里的body数据
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

//使用到的路由
app.use('/', indexRouter)
app.use('/users', usersRouter)

//代表允许任意域名跨域
const allowCrossDomain = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*') //自定义中间件，设置跨域需要的响应头。

    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE') //允许任何方法

    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token') //允许任何类型

    next() //一定要添加这段代码，不然程序无法正常往下执行
}
app.use(allowCrossDomain)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message
    res.locals.error = req.app.get('env') === 'development' ? err : {}

    // render the error page
    res.status(err.status || 500)
    res.render('error')
})

// module.exports = app;
//添加接口监听，然后bin目录就可以删掉没用了，之后使用node app.js就可以运行了 或者nodemon app.js
server.listen('5000')
